import Vue from 'vue'
import VueRouter from 'vue-router'

// 引入一级路由对应的组件
// import Register from '@/views/register'
// import Login from '@/views/login'
// import Detail from '@/views/detail'
import Layout from '@/views/layout'
// 引入二级路由对应的组件
// import Article from '@/views/article'
// import Collect from '@/views/collect'
// import Like from '@/views/like'
// import User from '@/views/user'

const Register = () => import(/* webpackChunkName: "register" */'@/views/register')
const Login = () => import(/* webpackChunkName: "login" */'@/views/login')
const Detail = () => import(/* webpackChunkName: "detail" */'@/views/detail')
const Article = () => import(/* webpackChunkName: "article" */'@/views/article')
const Collect = () => import(/* webpackChunkName: "collect" */'@/views/collect')
const Like = () => import(/* webpackChunkName: "like" */'@/views/like')
const User = () => import(/* webpackChunkName: "user" */'@/views/user')

// 引入获取本地存储中 token 的方法
import { getToken } from '@/utils/storage'

Vue.use(VueRouter)

const routes = [
  // 注册页路由规则
  { path: '/register', component: Register },
  // 登录页路由规则
  { path: '/login', component: Login },
  // 详情页路由规则
  { path: '/detail/:id', component: Detail },
  // 首页架子路由规则
  { 
    path: '/',
    redirect: '/article',
    component: Layout,
    children: [
      // 声明二级路由规则
      { path: 'article', component: Article },
      { path: 'collect', component: Collect },
      { path: 'like', component: Like },
      { path: 'user', component: User }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 登录权限控制
// 设置白名单页面：白名单指的是不需要登录就能访问的页面
const wihte_list = ['/login', '/register']
router.beforeEach((to, from, next) => {
  // 除了登录和注册不需要访问权限，其他页面想要访问必须先登录
  const token = getToken()
  if (token) {
    // token 存在，已经登录，直接放行
    next()
  } else {
    // token 不存在，没有登录
    // if (to.path === '/login' || to.path === '/register') {
    if (wihte_list.includes(to.path)) {
      // 要去的是登录或注册页，直接放行
      next()
    } else {
      // 要去不是登录或注册页，跳转到登录页去登录
      next('/login')
    }
  }
})

export default router
